<template>
    <div class="center-wrapper">
        <!-- 地铁线路 -->
        <div id="subLine-controller">
            <div class="title-bg">
                <i class="iconfont metro-lineRoute"></i> 地铁线路
            </div>
            <div class="item-wrapper">
                <div class="item" v-for="(item, index)  in subLineData" :key='index' @click.stop="handleItemClick(item)">
                    <div class="box" :style="{
                        borderColor: item.color,
                        backgroundColor: item.choosed ? item.color : 'rgba(0,0,0,0)',
                    }"></div>
                    <span :style="{ color: '#34c5cf' }">{{ item.name.slice(-3) }}</span>
                </div>
            </div>
        </div>
        <!-- 站点列表 -->
        <div id="station-controller">
            <div class="title-bg">
                <i class="iconfont metro-ditie"></i> 地铁站点
            </div>
            <div class="item-wrapper">
                <div class="item" :key="index" v-for="(item, index) in stationData">
                    <div class="box" :style="{
                        backgroundColor: index - 1 < metroIndex ? '#fff' : 'rgba(0,0,0,0)',
                    }"></div>
                    <span :style="{ color: '#34c5cf' }">{{ item.name }}</span>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref,onMounted,onBeforeUnmount } from 'vue'
import { useLineData } from '../store'
import { getPositions, getSiteTimes } from '@/cesiumTools/core'
import SimpleLabel from '@/cesiumTools/Bubble/htmlMarker'

const lineData = useLineData()
const subLineData = ref([])//全部线路信息
const stationData = ref([]);//当前线路的站点信息
const currentLine = ref({})//当前线路
const metroIndex = ref(0)//开始出发站点的索引
const siteTimes = ref([])//时间段数组
let viewer 
let trainEntity//列车实体
let popupController//气泡框

onMounted(()=>{
    subLineData.value = lineData.allData.map(item => ({ ...item, choosed: false }))
    viewer = lineData.Viewer
})

onBeforeUnmount(()=>{
    removeCurrentRoute()//清除副作用
})

// 线路点击事件
// 渲染列车，并添加漫游效果，这里需要从服务端获取到列车的实时信息
const handleItemClick = async (item)=>{
    // 如果点击的是同一个站线，返回
    if (currentLine.value?.name == item.name) return
    removeCurrentRoute()//先清除之前的副作用
    currentLine.value = item
    // 点击站线，更新数据，渲染轨道列车，视角跳转，渲染popup
    const { stationsList, id } = item;
    // 控制ui
    subLineData.value.forEach(item => {
        if (item.id == id) {
            item.choosed = true;
        } else {
            item.choosed = false
        }
    })
    stationData.value = stationsList;
    const trainInfo = await getTrainDataByLineId(id)// 从模拟服务端获取列车信息
    renderTrain(trainInfo) // 渲染轨道列车
    renderBubble(trainInfo) // 渲染气泡框
}

// 真实项目中的实时轨迹，webWorker开启一个新的线程，在这个线程中不断请求服务，更新位置
// cesium中使用callbackProperty更新位置，在两个动画之间，可能还要添加平滑函数
// 渲染气泡框
const renderBubble = (trainInfo) => {
    const { currentPosition, currentPassengers, lineName } = trainInfo
    const position=new Cesium.Cartesian3.fromDegrees(currentPosition.lng,currentPosition.lat)
    popupController=new SimpleLabel(viewer,{
        position,
        label:null,
        isShow:true,
        color:'#fff',
        scaleByDistance:null,
        offset:[130,205],
        // 使用相机高度优化该属性
        filterStructage:'height',
        attr:{
          currentPassengers,
          lineName
        },
        type:'carPopup'
    })
    popupController.addLabel()
}


// 假设从服务端获取到列车的实时信息
const getTrainDataByLineId = (id)=>{
    return new Promise((resolve,reject)=>{
        // 构造一个随机的站点index
        let startIndex = 0
        const startStationInfo = stationData.value[startIndex]//当前站点
        const endStationInfo = stationData.value[startIndex + 1]//下一站点
        // 由于站点坐标和路径坐标可能不会完全匹配，这里只是模拟数据，给列车虚构一个坐标点
        const trainData = {
            startIndex,//当前站点的索引
            currentPassengers: Math.ceil(Math.random() * 1000),//旅客数量
            startStation: startStationInfo,//当前站点
            destination: endStationInfo,//下一站点
            lineName: currentLine.value.name,//线路名称
            currentSpeed: Math.ceil(Math.random() * 100),//当前速度
            currentPosition: currentLine.value.paths[2],//当前列车位置
        }
        resolve(trainData)
    })
}

import * as Cesium from 'cesium'

// 渲染轨道列车
const renderTrain = (trainInfo)=>{
    // 获取出发站点，得到metroIndex
    const { startIndex,currentPosition, currentSpeed } = trainInfo
    metroIndex.value = startIndex
    // 当前列车位置在paths中的索引
    const pathIndex = currentLine.value.paths.findIndex(path=>path === currentPosition)
    // 获取property,相关时间
    const { property, startTime, endTime,siteTimes } = handlePosition(currentSpeed,pathIndex)
    // 创建列车实体
    trainEntity = viewer.entities.add({
        availability:new Cesium.TimeIntervalCollection([
            new Cesium.TimeInterval({
                start:startTime,
                stop:endTime,
            })
        ]),
        position:property,
        orientation:new Cesium.VelocityOrientationProperty(property),//自动调整朝向
        model:{
            scale:0.17,
            uri: "/src/assets/model/metro.gltf",
            minimumPixelSize: 40,
        },
    })
    siteTimes.value = siteTimes
    viewer.clock.shouldAnimate = true
    viewer.trackedEntity = trainEntity//将相机设置为自动追踪实体
    viewer.clock.startTime = startTime.clone()
    viewer.clock.stopTime = endTime.clone();
    viewer.clock.currentTime = startTime.clone();
     // 控制时间轴控件
    //viewer.timelineSelf.zoomTo(startTime.clone(),endTime.clone())
    // 监听时钟，如果列车到达站点，更新列车人数信息，并给一个暂停时间
    viewer.clock.onTick.addEventListener(tickEventHandler);
}


// 处理漫游效果，使用SampledProperty
const handlePosition = (speed,pathIndex)=>{
    const property = new Cesium.SampledProperty(Cesium.Cartesian3)
    let startTime = Cesium.JulianDate.fromDate(new Date())
    //通过当前位置索引得到后面的所有paths  ([{lng,lat},{lng,lat}...])
    const restPath = currentLine.value.paths.slice(pathIndex, currentLine.value.paths.length - 1)
    //转为Caterian3数组
    const positions = getPositions(restPath)
    // 根据速度计算总时间和每段时间
    const { siteTimes, timeSum } = getSiteTimes(positions, speed)
    const endTime = Cesium.JulianDate.addSeconds(
        startTime,timeSum,new Cesium.JulianDate()
    );
    // 创建property
    positions.forEach((position,index)=>{
        const time = Cesium.JulianDate.addSeconds(startTime,siteTimes[index],new Cesium.JulianDate())
        property.addSample(time, position);
    })
    return {
        property,startTime,endTime,siteTimes
    }
}

// 监听时钟变化事件
let apporachDistance=20//距离站点距离
const tickEventHandler = ()=>{
    const startPosition = trainEntity.position.getValue(viewer.clock.currentTime)
    // 通过当前时间，计算到达站点
    getCurrentStation(viewer.clock.currentTime)
    //通过当前的metroIndex和速度计算下一个站点的坐标
    const {position}=stationData.value[metroIndex.value + 1]
    const endPosition = new Cesium.Cartesian3.fromDegrees(position.lng,position.lat)
    if(startPosition && endPosition){
        // 计算列车和站点之间的距离
        let distance = Cesium.Cartesian3.distance(startPosition, endPosition);
        if(distance<apporachDistance){
            // 将列车暂停
            viewer.clock.shouldAnimate = false;
            // 2s后恢复
            setTimeout(() => {
               viewer.clock.shouldAnimate = true;
            }, 2000);
        }
         // 还需要通过startPosition计算气泡框坐标
        popupController && popupController.changePosition(startPosition)
    }else{
      // 如果列车已经到达终点站，需要取消全部事件
      removeCurrentRoute()
    }
}

// 计算到达站点的索引,更新ui显示
const getCurrentStation=(currentTime)=>{
    if(trainEntity.position._times.length){
        const times=trainEntity.position._times
        for(let i=0;i<times.length-1;i++){//i=489 property分割的坐标
            let nowTime=times[i]
            let nextTime=times[i+1]
            // compare(a,b)用于比较两个时间的前后
            // 返回1:a在b后 0:一样 -1:b在a后
            const compareNow=Cesium.JulianDate.compare(currentTime,nowTime)
            const compareNext=Cesium.JulianDate.compare(nextTime,currentTime)
            if(compareNow>0 && compareNext>0){
                //console.log(currentLine.value)//494个经纬度(线路段总体坐标)
                const targetPath=currentLine.value.paths[i]//找到线路的当前坐标
                if(targetPath){
                    const {name}=targetPath
                    const nameStr=name.split('-')[0]
                    // 通过名称，找到对应的站点的索引 (因为在线路段坐标中,好多个坐标同时对应一个name,所以可以准确找到,还方便更新)
                    // 不能直接通过position来找,因为stationData是每个站点的坐标,targetPath是线段的其中一个坐标,而且线路段坐标不一定跟站点坐标重合
                    const targetStationIndex=stationData.value.findIndex(station=>station.name===nameStr)
                    metroIndex.value=targetStationIndex
                }
            }
        }
    }
}

// 清除全部副作用
const removeCurrentRoute=()=>{
    // 释放视角
    viewer.trackedEntity=null
    trainEntity && viewer.entities.remove(trainEntity)
    popupController && popupController.removeMarker()
    tickEventHandler && viewer.clock.onTick.removeEventListener(tickEventHandler);
    viewer.clock.shouldAnimate = false
}
</script>

<style scoped>
.wrapper {
  width: 100%;
  height: 100%;
}

/* 地铁线路列表 */
#subLine-controller {
  position: absolute;
  bottom: 0;
  left: 32.5%;
  transform: translateX(-50%);
  width: 180px;
  height: 200px;
  background-color: rgba(0, 0, 0, 0.3);
  border: 1px solid #ab7818;
  display: flex;
  flex-direction: column;
}

.box {
  width: 10px;
  height: 10px;
  border-width: 1px;
  border-style: solid;
  background: transparent;
  user-select: all;
  cursor: pointer;
  transition: all 0.3s linear;
}

.item {
  width: 64.992px;
  height: 20.006px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 0.156vw;
  background-color: rgba(255, 255, 255, 0.2);
  border: 1px solid #885f12;
  color: #fff;
  font-size: 0.521vw;
  pointer-events: all;
}

.item:hover {
  border: 1px solid #d8961a;
}

.item > span {
  line-height: 0.469vw;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 2.083vw;
}

.item > input {
  outline: none;
  border: none;
  transition: all 0.3s ease;
}

.item-wrapper {
  display: flex;
  justify-content: space-around;
  align-content: space-around;
  flex-wrap: wrap;
  flex: 1;
  padding: 4px;
  overflow: hidden;
}

/* 站点列表 */
#station-controller {
  width: 600px;
  height: 200px;
  border: 1px solid #ab7818;
  background-color: rgba(0, 0, 0, 0.3);
  position: absolute;
  left: 38%;
  bottom: 0;
  color: #fff;
  display: flex;
  flex-direction: column;
}

#station-controller .item-wrapper {
  justify-content: flex-start;
}

#station-controller .item {
  margin: 0 7px;
}

.title-bg {
  width: 100%;
  height: 30px;
  background: url('/src/assets/uiResources/title-bg.png');
  background-size: contain;
  color: #fff;
  background-repeat: no-repeat;
  line-height: 30px;
  margin-left: 10px;
  background: rgb(255, 255, 255);
  background-image: linear-gradient(
    180deg,
    rgba(255, 255, 255, 1) 9%,
    rgba(211, 156, 50, 1) 57%
  );
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 站控措施图例 */
.right-wrapper {
  width: 11.417vw;
  height: 100%;
  position: absolute;
  right: 0px;
  top: 2.083vw;
}

.right-wrapper .query-item-title {
  cursor: default;
  pointer-events: none;
}

.right-wrapper .query-item-title::after {
  width: 20px;
  left: -20px;
}

.legend .query-item i {
  pointer-events: none;
  cursor: default;
}

.title {
  color: #fff;
}
</style>
